package com.manage.platform.config;

import com.manage.platform.constants.RedisPrefixConstants;
import com.manage.platform.context.UserContext;
import com.manage.platform.exception.CommonException;
import com.manage.platform.exception.EmError;
import com.manage.platform.utils.JwtTokenUtil;
import com.manage.platform.utils.RedisUtil;
import com.manage.platform.vo.UserDetailsVo;
import com.manage.platform.vo.UserVo;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * @author lk
 * 拦截器
 */
@AllArgsConstructor
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    private final RedisUtil redisUtil;
    private final PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 预处理回调方法，实现处理器的预处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //鉴权放行
        String requestURI = request.getRequestURI();
        for (String path : ExcludePaths.excludePath) {
            if (pathMatcher.match(path, requestURI)) {
                return true;
            }
        }
        // 解析token
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        String userId = JwtTokenUtil.validateToken(token);
        if (Objects.isNull(userId)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        // 获取用户信息
        UserVo userVo = (UserVo) redisUtil.getObject(RedisPrefixConstants.MANAGE_PLATFORM_USER_INFO + userId);
        if (Objects.isNull(userVo)) {
            throw new CommonException(EmError.AUTH_TOKEN_EXPIRED);
        }
        // 存入缓存
        UserContext.setUser(userVo);
        return true;
    }

    /**
     * 业务层处理
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {

    }

    /**
     * 整个请求处理完毕回调方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                @Nullable Exception ex) throws Exception {

    }

}
